package com.wuba.rxjavademo.lyz.day0416;

import java.util.concurrent.TimeUnit;

import rx.Observable;

/**
 * Created by liyaxing on 2016/4/18.
 */
public class Demo03 {

    public static void main(String[] ss){

        Demo03 demo03 = new Demo03() ;
        demo03.throttleObservable().subscribe(integer -> {
            print(integer);
        }) ;


    }

    private Observable<Integer> throttleObservable(){
        return createObservable().throttleLast(500,TimeUnit.MILLISECONDS) ;
    }

    private Observable<Integer> sampleObservable(){
        return createObservable().sample(500,TimeUnit.MILLISECONDS) ;
    }

    private Observable<Integer> skipObservable(){
        return Observable.just(1,2,3,5,6,6,7,8,7,6).skip(5) ;
    }

    private Observable<Integer> takeObservable(){
        return Observable.just(1,2,3,5,6,6,7,8,7,6).take(5) ;
    }

    private Observable<Integer> firstObservable(){
        return Observable.just(1,2,3,5,6,6,7,8,7,6).first(integer -> integer > 5) ;
    }

    private Observable<Integer> filterObservable(){
        return Observable.just(1,2,3,5,6,6,7,8,7,6).filter(integer -> integer > 5) ;
    }

    private Observable<Integer> elementAtObservable(){
        return Observable.just(1,2,3,5,6,6,7,8,7,6).elementAt(3) ;
    }

    private Observable<Integer> distinctUntilChangeObservable(){
        return Observable.just(1,2,3,5,6,6,7,8,7,6).distinctUntilChanged() ;
    }

    private Observable<Integer> distinctObservable(){
        return Observable.just(1,2,3,4,5,6,7,8,7,6).distinct() ;
    }

    private Observable<Integer> debounceObservable(){
        return Observable.just(1,2,3,4,5,6,7,8,9).debounce(integer -> Observable.create(subscriber -> {

            if(integer % 2 == 0){
                subscriber.onNext(integer * 2);
            }

        })) ;
    }

    private Observable<Integer> throttleWithTimeoutObservable(){
        return createObservable().throttleWithTimeout(200, TimeUnit.MILLISECONDS) ;
    }


    private Observable<Integer> createObservable(){
        return Observable.create(subscriber -> {
            for (int i = 0; i < 20; i++) {

                if(!subscriber.isUnsubscribed())
                    subscriber.onNext(i);

                int sleepTime = 100 ;
                if(i % 3 == 0){
                    sleepTime = 300;
                }

                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            subscriber.onCompleted();
        }) ;
    }

    private static void print(Object obj){
        System.out.println(obj) ;
    }


}
